<template>
	<div>
		<div class="pdf-preview">
			<div class="pdf-wrap">
				<vue-pdf-embed :source="state.source" :style="scaleFun" class="vue-pdf-embed" :page="state.pageNum" />
			</div>
		</div>
		<div class="page-tool">
			<div class="page-tool-item" @click="lastPage">上一页</div>
			<div class="page-tool-item" @click="nextPage">下一页</div>
			<div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
			<div class="page-tool-item" @click="pageZoomOut">放大</div>
			<div class="page-tool-item" @click="pageZoomIn">缩小</div>
		</div>
	</div>
</template>
<script setup>
import { computed, reactive, toRefs, watch } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
// 引入插件
import * as pdfjsLib from 'pdfjs-dist'
//定义

const prop = defineProps({
	url: {
		type: String
	}
})
const { url } = toRefs(prop)
const state = reactive({
	source: '',
	pageNum: 1, //当前页面
	scale: 1, // 缩放比例
	numPages: 0 // 总页数
})
watch(url, () => {
	if (url.value) {
		getPdfUrl(url.value)
	}
})
function getPdfUrl(data) {
	state.source = data
	pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
	const loadingTask = pdfjsLib.getDocument(data)
	loadingTask.promise.then((pdf) => {
		state.numPages = pdf.numPages
	})
}
const scaleFun = computed(() => `transform:scale(${state.scale})`)

function lastPage() {
	if (state.pageNum > 1) {
		state.pageNum -= 1
	}
}
function nextPage() {
	if (state.pageNum < state.numPages) {
		state.pageNum += 1
	}
}
function pageZoomOut() {
	if (state.scale < 2) {
		state.scale += 0.1
	}
}
function pageZoomIn() {
	if (state.scale > 1) {
		state.scale -= 0.1
	}
}
</script>
<style lang="scss" scoped>
.page-tool {
	display: flex;
	position: absolute;
	top: 5px;
	left: 50%;
	z-index: 100;
	transform: translateX(-50%);
	align-items: center;
	background: rgb(66 66 66);
	color: white;
	border-radius: 19px;
	cursor: pointer;
	justify-content: center;
	font-size: 15px;
}
.page-tool-item {
	padding: 4px 10px;
	cursor: pointer;
}
</style>
